package cn.xw.utils;

import cn.xw.entity.Student;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

public class StreamUtils {

    static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object,Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * Get timeDay base 0 offset
     *
     * @param formatStr e.g: YYYY-MM-dd HH:mm:ss
     * @param offsetInSeconds offset
     * @return formatted day
     */
    public String getTimeDay(String formatStr, int offsetInSeconds) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr);
        Calendar calendar = Calendar.getInstance();
        int offset = OffsetDateTime.now().getOffset().getTotalSeconds();
        calendar.setTime(new Date(System.currentTimeMillis() -offset*1000 + offsetInSeconds*1000));
        return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        {
            list.add(new Student(1L, "Core Java", 20, "Beijing", 100.0));
            list.add(new Student(1L, "Core Java", 20, "Beijing1", 90.0));
            list.add(new Student(1L, "Java", 19, "zhangsan", 100.0));
            list.add(new Student(1L, "Jax", 20, "lisi", 100.0));
            list.add(new Student(1L, "Core C", 20, "wangwu", 100.0));
        }
        list.stream().filter(distinctByKey(b -> b.getName())).forEach(b -> System.out.println(b.getName()+ "," + b.getAddress()));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        int offset = OffsetDateTime.now().getOffset().getTotalSeconds();
        calendar.setTime(new Date(System.currentTimeMillis() -offset*1000 + 28800000L));
        System.out.println(simpleDateFormat.format(new Date(calendar.getTimeInMillis())));
    }
}
